package leetcode;

public class LC206 {

    public ListNode reverseList(ListNode head) {

        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;

        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;

    }



    public static ListNode partition(ListNode head, int x) {


        // 将链表中小于x的节点从原链表中断开，形成一个新链表
        ListNode newHead = new ListNode();
        ListNode newListCur = newHead;

        //需要删除链表中小于x的节点，所以需要记录下来当前节点cur和之前的节点pre
        //head节点可能被删除，所以需要记录新的head节点
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;

        while (cur != null) {
            if (cur.val < x) {
                newListCur.next = cur;
                newListCur = cur;
                if (head == cur) head = cur.next;
                if (pre != null) pre.next = cur.next;
                next = cur.next;
                cur.next = null;
                cur = next;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        newListCur.next = head;
        return newHead.next;
    }

    public static void main(String[] args) {
        ListNode listNode6 = new ListNode(2,null);
        ListNode listNode5 = new ListNode(5,listNode6);
        ListNode listNode4 = new ListNode(2,listNode5);
        ListNode listNode3 = new ListNode(3,listNode4);
        ListNode listNode2 = new ListNode(4,listNode3);
        ListNode listNode1 = new ListNode(1,listNode2);
        ListNode head = partition(listNode1,3);
        while (head != null) {
            System.out.println(head.val);
            head = head.next;
        }
    }
}

